
// 绑定事件
export const on = (function () {
  if (!document.addEventListener) { // 兼容ie
    return function (element: EventTarget, event: string, handler: (event: Event) => any) {
      if (element && event && handler) {
        (element as any).attachEvent('on' + event, handler)
      }
    }
  } else {
    return function (element: EventTarget, event: string, handler: (event: Event) => any) {
      if (element && event && handler) {
        element.addEventListener(event, handler, false)
      }
    }
  }
})()

// 解除事件绑定
export const off = (function () {
  if (!document.removeEventListener) { // 兼容ie
    return function (element: EventTarget, event: string, handler: (event: Event) => any) {
      if (element && event) {
        (element as any).detachEvent('on' + event, handler)
      }
    }
  } else {
    return function (element: EventTarget, event: string, handler: (event: Event) => any) {
      if (element && event) {
        element.removeEventListener(event, handler, false)
      }
    }
  }
})()

// 获取MouseEvent.path 针对浏览器兼容性兼容ie11,edge,chrome,firefox,safari
export const eventPath = function (evt: Event):EventTarget[] {
  const path = Array.from((evt.composedPath && evt.composedPath()) || (evt as any).path)
  const target = evt.target as EventTarget
  if (path != null) {
    return path.indexOf(window) < 0 ? path.concat(window) : path
  }
  if (target === window) {
    return [window]
  }
  function getParents (node: Node, memo?: Node[]): Node[] {
    memo = memo || []
    const parentNode = node.parentNode
    if (!parentNode) {
      return memo
    } else {
      return getParents(parentNode, memo.concat(parentNode))
    }
  }
  return [target].concat(getParents(target as Node), window)
}
